package com.yuda.tools.log.controller;


import com.alibaba.fastjson.JSONArray;
import com.yuda.common.core.constant.HttpStatus;
import com.yuda.common.core.utils.StringUtils;
import com.yuda.common.core.utils.file.FileUtils;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.web.page.PageDomain;
import com.yuda.common.core.web.page.TableDataInfo;
import com.yuda.common.core.web.page.TableSupport;
import com.yuda.tools.log.entity.PicDpi;
import com.yuda.tools.log.entity.RenderQueryResult;
import com.yuda.tools.log.entity.Subject;
import com.yuda.tools.log.entity.XuanRan_Result;
import com.yuda.tools.log.service.RenderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

//渲染答案
@RestController
@RequestMapping(value = "/rendering")
public class RenderingAnswersController extends BaseController {
    @Autowired
    private RenderService renderService;


    @Autowired
    private JdbcTemplate jdbcTemplate;
    private Map<String, XuanRan_Result> map = new HashMap<>();
    private Map<String, String> map2 = new HashMap<>();
    private Map<String, String> quesTitle = new HashMap<>();

    @Value("${server.port}")
    private Integer serverPort;

    private final AtomicBoolean canRun = new AtomicBoolean(true);

    //如果type 传了并且 是1 则合并题目， 但是 这个时候 quesIds 一定是2道题，否则直接返回
    @GetMapping(value = {"/readDB/{zkzNum}", "/readDB"}) //20190309
    public synchronized AjaxResult renderingAnswers(@RequestParam("quesIds") String[] quesIds,
                                                    @PathVariable(value = "zkzNum", required = false) String zkzNum,
                                                    @RequestParam(value = "type", required = false) String type) {
        if (!canRun.get()) {
            return AjaxResult.error();
        }

        canRun.set(false);

        long startMs = System.currentTimeMillis();

        int c = 0;

        //得到待渲染的对象集合
        List<XuanRan_Result> results = results(quesIds, zkzNum);

        if (!StringUtils.isEmpty(type) && type.equals("1") && quesIds.length == 2) {
            //重新给results 赋值
            String headerParent = "<div style=\"width:960px;margin:0 auto;padding:20px;\">";
            String header = "<div style=\"float:left;width:460px;margin-right:40px;\">";
            String header1 = "<div style=\"float:left;width:460px\">";
            String footer = "</div>";
            String footerParent = "</div>";

            List<XuanRan_Result> mergeResults = new ArrayList<>();
            Map<String, List<XuanRan_Result>> collect = results.stream().collect(Collectors.groupingBy(XuanRan_Result::getZkzNum));
            for (String key : collect.keySet()) {
                List<XuanRan_Result> xuanRan_results = collect.get(key);
                XuanRan_Result xuanRan_result = xuanRan_results.get(0);
                XuanRan_Result xuanRan_result1 = xuanRan_results.get(1);
                String all = xuanRan_result.getAll();
                all = headerParent + header + all + footer + header1 + xuanRan_result1.getAll() + footer + footerParent;
                xuanRan_result.setAll(all);
                mergeResults.add(xuanRan_result);
            }
            results = mergeResults;

            for (XuanRan_Result result : results) {
                map2.put(result.getZkzNum(), result.getAll());
            }
        }

        Map<String, Integer> zkzMap = new HashMap<>();

        //没输入准考证号则渲染所有学生
        try {
            for (int i = 0; i < results.size(); i++) {
                if (zkzNum == null) {
                    zkzNum = results.get(i).getZkzNum();//若准考证号为空，需要重新获取。
                }
                String quesId = results.get(i).getQuesId();
                Integer integer = zkzMap.get(zkzNum);
                int quesIdx = 1;
                if (integer != null) {
                    quesIdx = integer + 1;
                    zkzMap.put(zkzNum, quesIdx);
                } else {
                    zkzMap.put(zkzNum, 1);
                }
                String filePath;
                //核心
                final Runtime rt = Runtime.getRuntime();
                String system = System.getProperty("os.name");
                String s = system.toLowerCase();
                System.out.println("当前正在渲染的准考证是：" + zkzNum + "   " + ++c);
                if (s.contains("windows")) {
                    filePath = "D:\\qct0628\\" + results.get(i).getSubjectRelationId() + "\\" + zkzNum + "\\" + quesIdx + ".png";
                    try {
                        String url = "D:/phantomjs/js/phtomjs.js http://localhost:" + serverPort + "/rendering/render?zkzNum=" + zkzNum + "&quesId=" + quesId;
                        if (type != null && type.equals("1")) url += "&type=1";
                        rt.exec("D:\\phantomjs_window\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe  " + url + " " + filePath);//win本地的phantomjs目录
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (s.contains("linux")) {
                    filePath = "D:/qct0628/" + results.get(i).getStudentId() + "/" + zkzNum + "/" + quesIdx + ".png";
                    try {
                        rt.exec("D:/phantomjs_linux/phantomjs-2.1.1-linux/bin/phantomjs  " +
                                "D:/phantomjs/js/phtomjs.js http://localhost:" + serverPort + "/rendering/render?zkzNum=" + zkzNum + "&quesId=" + quesId + " " + filePath);//win本地的phantomjs目录
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (type != null && type.equals("1") && quesIds.length == 2) {

                    String res = "(";
                    for (int t = 0; t < quesIds.length; t++) {
                        if (t < quesIds.length - 1) {
                            res = res + quesIds[t] + ",";
                        } else
                            res = res + quesIds[t] + ")";
                    }
                    String sq1 = "update tsinghua_formal_answer set render_status=2 where zkz_num = '" + zkzNum + "' and ques_id in " + res;
                    jdbcTemplate.update(sq1);

                    //查询某2题的条数
                    String sql2 = "select render_status from tsinghua_formal_answer a where a.ques_id in " + res;
                    List<Long> list2 = jdbcTemplate.queryForList(sql2, Long.class);
                    //查询某2题已渲染的条数
                    String sql3 = "select render_status from tsinghua_formal_answer a where a.ques_id in " + res + " and a.render_status != 0";
                    List<Long> list3 = jdbcTemplate.queryForList(sql3, Long.class);
                    //若相等代表该2题已经全部渲染完成,更新所有状态码为：1
                    if (list2.size() == list3.size()) {
                        String sql4 = "update tsinghua_formal_answer set render_status = 1 where ques_id in " + res;
                        jdbcTemplate.update(sql4);
                    }

                } else {
                    String sq1 = "update tsinghua_formal_answer set render_status=2 where zkz_num = '" + zkzNum + "' and ques_id=" + quesId;
                    jdbcTemplate.update(sq1);

                    //查询某一题的条数
                    String sql2 = "select render_status from tsinghua_formal_answer a where a.ques_id = " + quesId;
                    List<Long> list2 = jdbcTemplate.queryForList(sql2, Long.class);
                    //查询某一题已渲染的条数
                    String sql3 = "select render_status from tsinghua_formal_answer a where a.ques_id = " + quesId + " and a.render_status != 0";
                    List<Long> list3 = jdbcTemplate.queryForList(sql3, Long.class);
                    //若相等代表该题已经全部渲染完成,更新所有状态码为：1
                    if (list2.size() == list3.size()) {
                        String sql4 = "update tsinghua_formal_answer set render_status = 1 where ques_id = " + quesId;
                        jdbcTemplate.update(sql4);
                    }
                }
                zkzNum = null;//重新置空，否则下次zkzNum就会保留上次的值，不再是空了，会出错。

                //休眠0.5秒，保证渲染的完整性。
                try {
                    Thread.sleep(500);//休眠0.5秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            canRun.set(true);
        }
        long endMs = System.currentTimeMillis();
        System.out.println("Time elapsed:" + ms2DHMS(startMs, endMs));

        return AjaxResult.success();
    }


    private static String ms2DHMS(long startMs, long endMs) {
        String retval = null;
        long secondCount = (endMs - startMs) / 1000;
        String ms = (endMs - startMs) % 1000 + "ms";

        long days = secondCount / (60 * 60 * 24);
        long hours = (secondCount % (60 * 60 * 24)) / (60 * 60);
        long minutes = (secondCount % (60 * 60)) / 60;
        long seconds = secondCount % 60;

        if (days > 0) {
            retval = days + "d" + hours + "h" + minutes + "m" + seconds + "s";
        } else if (hours > 0) {
            retval = hours + "h" + minutes + "m" + seconds + "s";
        } else if (minutes > 0) {
            retval = minutes + "m" + seconds + "s";
        } else if (seconds > 0) {
            retval = seconds + "s";
        } else {
            return ms;
        }

        return retval + ms;
    }


    @GetMapping("/preview/{zkzNum}/{quesId}")
    public void preview(
            @PathVariable(value = "zkzNum") String zkzNum, @PathVariable(value = "quesId") String quesId,
            HttpServletResponse response) throws Exception {

        System.out.println("preview ... " + zkzNum + " " + quesId);
        String filePath = null;
        //通过科目id和zkzNum和quesId找出对象，获取其科目名称
        RenderQueryResult result = renderService.getByZkzNum(zkzNum, quesId);
        System.out.println(result);

        if (result == null) {
            File file = new File("/111.png");
            FileUtils.writeBytes(file.getAbsolutePath(), response.getOutputStream());
            return;
        }

        String system = System.getProperty("os.name");
        String s = system.toLowerCase();
        if (s.contains("windows")) {
            filePath = "D:\\qct0628\\" + result.getSubjectId() + "\\" + zkzNum + "\\" + "1.png";
        } else if (s.contains("linux")) {
            filePath = "/root/officialbackend/modules/modules-tools/modules-tools-render/D:/qct0628/" + result.getSubjectId() + "/" + zkzNum + "/1.png";
        }

        assert filePath != null;
        File file = new File(filePath);
        System.out.println(filePath);
        if (!file.exists()) {
            File file2 = new File("/111.png");
            FileUtils.writeBytes(file2.getAbsolutePath(), response.getOutputStream());
        } else {
            System.out.println("文件存在: " + file.getAbsolutePath());
        }
        FileUtils.writeBytes(filePath, response.getOutputStream());
    }


    //处理要渲染字符转里面的标签
    @GetMapping("/render")
    public String one(String zkzNum, String quesId, String type) {
        if (type != null && type.equals("1")) {
            return map2.get(zkzNum);
        }
        XuanRan_Result xuanRan_result = map.get(quesId + "_" + zkzNum);
        return xuanRan_result.getAll();
    }


    //得到所有科目
    @GetMapping("/subjects")
    public List<Subject> getSubjectName() {

        List<Subject> subjectList = renderService.getSubjectName();
        return subjectList;
    }

    //根据科目id得到给科目所有的题号
    @PostMapping("/quesId")
    public List<Long> getQuesId(@RequestBody Subject subject) {

        Long subjectId = subject.getId();
        List<Long> quesidList = renderService.getQuesId(subjectId);
        return quesidList;
    }

    @GetMapping("/seek1")
    public TableDataInfo seek1(@RequestParam(value = "subjectId", required = false) String subjectId,
                               @RequestParam(value = "quesId", required = false) String quesId,
                               @RequestParam(value = "renderStatus", required = false) String renderStatus) {

        List<RenderQueryResult> list = new ArrayList<>();
        //存部分渲染的quesId
        List<Integer> partRenderQuesIdList = new ArrayList<>();

        //得到部分渲染的信息，取出其题目id
        List<RenderQueryResult> partRender = renderService.getPartRender();
        for (RenderQueryResult result : partRender) {
            int i = Integer.parseInt(result.getQuesId());
            partRenderQuesIdList.add(i);
        }

        int[] arr = partRenderQuesIdList.stream().mapToInt(Integer::intValue).toArray();
        String result1 = null;
        if (arr.length != 0) {
            result1 = "(";
            for (int i = 0; i < arr.length; i++) {
                if (i < arr.length - 1) {
                    result1 = result1 + arr[i] + ",";
                } else
                    result1 = result1 + arr[i] + ")";
            }
        }


        if (renderStatus != null && renderStatus.equals("0")) {
            //若一题有部分学生渲染，则状态值会有0和2，此时应把该题归入状态值2（部分渲染）
            list = renderService.getMessage2(subjectId, quesId, renderStatus, result1);
        } else {
            list = renderService.getMessage(subjectId, quesId, renderStatus);
        }

        List<RenderQueryResult> newList = new ArrayList<>();
        for (RenderQueryResult result : list) {
            //查询某一题的条数
            String sql1 = "select render_status from tsinghua_formal_answer a where a.type in (6,7,8) and a.ques_id = " + result.getQuesId();
            //查询某一题已渲染的条数
            String sql2 = "select render_status from tsinghua_formal_answer a where a.type in (6,7,8) and a.ques_id = " + result.getQuesId() + " and a.render_status!=0";
            //统计某一题的条数
            String sql3 = "select count(render_status) from tsinghua_formal_answer a where a.type in (6,7,8) and a.ques_id = " + result.getQuesId();


            List<Long> list1 = jdbcTemplate.queryForList(sql1, Long.class);
            List<Long> list2 = jdbcTemplate.queryForList(sql2, Long.class);
            Integer countRender = jdbcTemplate.queryForObject(sql3, Integer.class);
            String count = String.valueOf(countRender);

            //若某一题的条数=已渲染的条数
            if (list1.size() == list2.size()) {
                result.setRenderStatus("1");//该题已渲染完成
                result.setRenderCount(count);//渲染总量就是该题的条数
            } else {
                if (list2.size() == 0) {
                    result.setRenderStatus("0");//该题未渲染
                    result.setRenderCount("0");//渲染总量是0
                } else {
                    result.setRenderStatus("2");//该题部分渲染
                    result.setRenderCount(String.valueOf(list2.size()));//渲染总量是list2的大小
                }
            }
            newList.add(result);
        }

        //自定义分页
        int total = newList.size();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        int fromIndex = (pageNum - 1) * pageSize;
        if (fromIndex > total) {
            int yuShu = total % pageSize;
            newList = newList.subList(total - yuShu, total);
        } else {
            int toIndex = pageNum * pageSize;
            if (toIndex > total) {
                toIndex = total;
            }
            newList = newList.subList(fromIndex, toIndex);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(newList);
        rspData.setMsg("查询成功");
        rspData.setTotal(total);

        return rspData;
    }


    @GetMapping("/seek2")
    public TableDataInfo seek2(@RequestParam(value = "studentName", required = false) String studentName,
                               @RequestParam(value = "sfzNum", required = false) String sfzNum,
                               @RequestParam(value = "zkzNum", required = false) String zkzNum,
                               @RequestParam(value = "subjectId", required = false) String subjectId,
                               @RequestParam(value = "quesId", required = false) String quesId,
                               @RequestParam(value = "renderStatus", required = false) String renderStatus) {

        String[] RenderArr = new String[]{};
        if (!StringUtils.isEmpty(renderStatus) && renderStatus != null) {
            RenderArr = renderStatus.split(",");
        } else {
            RenderArr = null;
        }
        List<RenderQueryResult> stuMessageList = renderService.getStuMessage(studentName, sfzNum, zkzNum, subjectId, quesId, RenderArr);

        //自定义分页
        int total = stuMessageList.size();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        int fromIndex = (pageNum - 1) * pageSize;
        if (fromIndex > total) {
            int yuShu = total % pageSize;
            stuMessageList = stuMessageList.subList(total - yuShu, total);
        } else {
            int toIndex = pageNum * pageSize;
            if (toIndex > total) {
                toIndex = total;
            }
            stuMessageList = stuMessageList.subList(fromIndex, toIndex);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(stuMessageList);
        rspData.setMsg("查询成功");
        rspData.setTotal(total);

        return rspData;

    }


    @GetMapping("/detailMessage")
    public AjaxResult detailMessage(@RequestParam(value = "subjectName", required = true) String subjectName,
                                    @RequestParam(value = "quesId", required = true) String quesId) {

        startPage();//分页
        List<RenderQueryResult> detailList = renderService.getDetail(subjectName, quesId);
        return AjaxResult.success(detailList);
    }


    //返回待渲染的对象集合
//    @RequestMapping(value = "/readDB") //20190309
    public List<XuanRan_Result> results(String[] quesIds, String zkzNum) {


        if (quesTitle.isEmpty()) {
            quesTitle.put("175", "请结合你填报的强基综合素质材料及专业志愿，就以下问题进行阐述。\n" +
                    "\n" +
                    "强基计划中你的第一专业志愿是什么？请你描绘该专业学习、研究及应用的内容，可结合身边事例举例说明。你觉得你的哪些特点或优势对你学习该专业最有帮助？（500字以内）");
            quesTitle.put("139", "请结合你填报的强基综合素质材料及专业志愿，就以下问题进行阐述。\n" +
                    "\n" +
                    "强基计划中你的第一专业志愿是什么？请你描绘该专业学习、研究及应用的内容，可结合身边事例举例说明。你觉得你的哪些特点或优势对你学习该专业最有帮助？（500字以内）");
            quesTitle.put("286", "阅读下文，并依据你的专业志愿及申请材料，阐述你的专业选择原因，并分享你的梦想。题目自拟，文体不限。（500字以内）");

            quesTitle.put("140", "阅读下文，并依据你的专业志愿及申请材料，阐述你的专业选择原因，并分享你的梦想。题目自拟，文体不限。（500字以内）");
        }


        List<XuanRan_Result> ResultList = new ArrayList<>();
        String result = "(";
        for (int i = 0; i < quesIds.length; i++) {
            if (i < quesIds.length - 1) {
                result = result + quesIds[i] + ",";
            } else
                result = result + quesIds[i] + ")";
        }

        //若准考证不为空但是搜索结果为空，可能是输入的zkzNum不存在。
        if (zkzNum != null) {

            List<PicDpi> PicDpis = jdbcTemplate.query("select a.zkz_num,d.name student_name,a.subject_relation_id,CONCAT(c.desc,c.name) subject_name," +
                    "a.ques_id,b.question_index question_index,b.title,b.type,e.content,a.answer,a.answer_json as answerJson " +
                    "from tsinghua_formal_answer a\n" +
                    "left join sparta_exam_subject_student o\n" +
                    "on a.zkz_num = o.zkz_num\n" +
                    "left join sparta_paper_question b\n" +
                    "on a.ques_id=b.ques_id\n" +
                    "left join sparta_subject c\n" +
                    "on a.subject_relation_id=c.id\n" +
                    "left join sparta_exam_student d\n" +
                    "on a.zkz_num=d.zkz_num\n" +
                    "left join specquestion e\n" +
                    "on d.sfz_num = e.sfz\n" +
                    " where o.quekao = 0 and a.type in (6,7,8) and d.province_id != 11 and a.ques_id in" + result + " and a.zkz_num =" + "'" + zkzNum + "'" +
                    " GROUP BY a.zkz_num,a.ques_id", new BeanPropertyRowMapper<>(PicDpi.class));

            //给PicDpis的fileName字段赋值，值 = Ranklist的rank
            for (PicDpi pic : PicDpis) {

                XuanRan_Result XuanRan = new XuanRan_Result();

                if (pic.getAnswerJson() == null)
                    continue;

                List<PicDpi> picDpis = JSONArray.parseArray(pic.getAnswerJson(), PicDpi.class);

                PicDpi p = picDpis.get(0);
                p.setQuestionIndex(pic.getQuestionIndex());
                p.setTitle(pic.getTitle());

                String questionIndex = p.getQuestionIndex();
                String title = p.getTitle();


                int type = pic.getType();
                String content = pic.getContent();

//                System.out.println("Oldtitle================>:" + title);

                String Newtitle = title;

                if (type == 8) {
//                    Newtitle = title.replace("%@", content);//若type=8，题目中的   %@   换成  content  的内容。
                    Newtitle = quesTitle.get(pic.getQuesId());
                }
//                System.out.println("Newtitle================>:" + Newtitle);


                String oldAnswer = p.getAnswer();
                String answer1 = oldAnswer.replaceAll("\n", "<br/>");
                String answer = answer1.replaceAll("  ", "&nbsp&nbsp");
                answer = "<div style=\"line-height: 2.0;\">" + answer + "</div>";
                int countAnswer = getMSWordsCount(oldAnswer.trim());


                String timu = "第" + questionIndex + "题:" + "<br/>" + Newtitle;


                //1320 * 852

                //渲染格式：
                String all = timu
                        + "<br/><br/>" + "答案如下："
                        + "<br/>" + answer     //题目  +   答案；
                        + "<br/><br/>" + "答案字数：" + countAnswer;

//            all = all.replaceAll("src=\"", "src=\"" + "C:/Users/AI_Win10/Desktop/");
                XuanRan.setQuesId(pic.getQuesId());
                XuanRan.setQuestionIndex(pic.getQuestionIndex());
                XuanRan.setSubjectRelationId(pic.getSubjectRelationId());
                XuanRan.setSubjectName(pic.getSubjectName());
                XuanRan.setZkzNum(pic.getZkzNum());
                XuanRan.setAll(all);

                ResultList.add(XuanRan);
                map.put(pic.getQuesId() + "_" + pic.getZkzNum(), XuanRan);
            }
        } else {
//            List<PicDpi> PicDpis = jdbcTemplate.query("SELECT a.subject_relation_id,a.ques_id,a.ques_index question_index,b.zkz_num,\n" +
//                    "e.name student_name,d.name subject_name,a.answer,a.answer_json,f.question_id,f.title\n" +
//                    "FROM tsinghua_formal_answer a\n" +
//                    "left JOIN sparta_exam_student b on  a.student_id = b.student_id\n" +
//                    "left JOIN sparta_subject d on a.subject_relation_id = d.id\n" +
//                    "LEFT JOIN excel_student2019 e on b.zkz_num = e.zkz_num\n" +
//                    "left join dp_ques_index_mapping f on a.ques_id = f.question_id\n" +
//                    "where  a.ques_id in " + result + " ORDER BY ques_id asc", new BeanPropertyRowMapper<>(PicDpi.class));

            List<PicDpi> PicDpis = jdbcTemplate.query("select a.zkz_num,d.name student_name,a.subject_relation_id,CONCAT(c.desc,c.name) subject_name," +
                    "a.ques_id,b.question_index question_index,b.title,b.type,e.content,a.answer,a.answer_json\n" +
                    "from tsinghua_formal_answer a\n" +
                    "left join sparta_exam_subject_student o\n" +
                    "on a.zkz_num = o.zkz_num\n" +
                    "left join sparta_paper_question b\n" +
                    "on a.ques_id=b.ques_id\n" +
                    "left join sparta_subject c\n" +
                    "on a.subject_relation_id=c.id\n" +
                    "left join sparta_exam_student d\n" +
                    "on a.zkz_num=d.zkz_num\n" +
                    "left join specquestion e\n" +
                    "on d.sfz_num = e.sfz\n" +
                    " where o.quekao = 0 and a.type in (6,7,8) and d.province_id != 11 and a.ques_id in" + result + "  GROUP BY a.zkz_num,a.ques_id", new BeanPropertyRowMapper<>(PicDpi.class));


            //给PicDpis的fileName字段赋值，值 = Ranklist的rank
            for (PicDpi pic : PicDpis) {

                XuanRan_Result XuanRan = new XuanRan_Result();
                List<PicDpi> picDpis = JSONArray.parseArray(pic.getAnswerJson(), PicDpi.class);

                PicDpi p = picDpis.get(0);
                p.setQuestionIndex(pic.getQuestionIndex());
                p.setTitle(pic.getTitle());
                String questionIndex = p.getQuestionIndex();
                String title = p.getTitle();


                int type = pic.getType();
//                String content = pic.getContent();

//                System.out.println("Oldtitle================>:" + title);

                String Newtitle = title;

                if (type == 8) {
//                    Newtitle = title.replace("%@", content);//若type=8，题目中的   %@   换成  content  的内容。
                    Newtitle = quesTitle.get(pic.getQuesId());
                }
//                System.out.println("Newtitle================>:" + Newtitle);


                String oldAnswer = p.getAnswer();
                String answer1 = oldAnswer.replaceAll("\n", "<br/>");
                String answer = answer1.replaceAll("  ", "&nbsp&nbsp");
                answer = "<div style=\"line-height: 2.0;\">" + answer + "</div>";
                int countAnswer = getMSWordsCount(oldAnswer.trim());


                String timu = "第" + questionIndex + "题:" + "<br/>" + Newtitle;


                //渲染格式：
                String all = timu
                        + "<br/><br/>" + "答案如下："
                        + "<br/>" + answer     //题目  +   答案；
                        + "<br/><br/>" + "答案字数：" + countAnswer;


//            all = all.replaceAll("src=\"", "src=\"" + "C:/Users/AI_Win10/Desktop/");
                XuanRan.setQuesId(pic.getQuesId());
                XuanRan.setQuestionIndex(pic.getQuestionIndex());
                XuanRan.setSubjectRelationId(pic.getSubjectRelationId());
                XuanRan.setSubjectName(pic.getSubjectName());
                XuanRan.setZkzNum(pic.getZkzNum());
                XuanRan.setAll(all);

                ResultList.add(XuanRan);
                map.put(pic.getQuesId() + "_" + pic.getZkzNum(), XuanRan);
            }
        }
        return ResultList;
    }


    //统计答案字数
    public int getMSWordsCount(String context) {
        int words_count = 0;
//中文单词

        String cn_words = context.replaceAll("[^(\\u4e00-\\u9fa5，。《》？；’‘：“”【】、)(……￥！·)]", "");

        int cn_words_count = cn_words.length();

//非中文单词

        String non_cn_words = context.replaceAll("[^(a-zA-Z0-9`\\-=\';.,/~!@#$%^&*()_+|}{\":>\\[\\])]", " ");

        int non_cn_words_count = 0;

        String[] ss = non_cn_words.split(" ");

        for (String s : ss) {
            if (s.trim().length() != 0) non_cn_words_count++;

        }

//中文和非中文单词合计

        words_count = cn_words_count + non_cn_words_count;

        return words_count;

    }

}



